<template>
    <div>
<!--      //中间的box-->
      <div style="width: 180px;height: 600px;float: left;background-color: #e3e1e1">
        <div class="chatBox_header">
          <el-input
            style="width: 140px!important;float: left;margin-right: 5px"
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            v-model="searchInfo">
          </el-input>
          <svg @click="addFriend()" t="1623120747902" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1200" width="26" height="26"><path d="M904.704 763.392h-276.48c-10.752 0-19.456-8.704-19.456-19.456 0-10.752 8.704-19.456 19.456-19.456h276.48c10.752 0 19.456 8.704 19.456 19.456 0 10.752-8.704 19.456-19.456 19.456z" fill="#8a8a8a" p-id="1201"></path><path d="M766.464 901.632c-10.752 0-19.456-8.704-19.456-19.456v-276.48c0-10.752 8.704-19.456 19.456-19.456s19.456 8.704 19.456 19.456v276.48c0 10.752-8.704 19.456-19.456 19.456zM498.688 526.336c-112.64 0-204.288-91.648-204.288-204.288S386.048 117.76 498.688 117.76s204.288 91.648 204.288 204.288-91.648 204.288-204.288 204.288z m0-369.664c-91.136 0-165.376 74.24-165.376 165.376 0 91.136 74.24 165.376 165.376 165.376 91.136 0 165.376-74.24 165.376-165.376 0-91.136-74.24-165.376-165.376-165.376z" fill="#8a8a8a" p-id="1202"></path><path d="M121.856 894.464c-10.752 0-19.456-8.704-19.456-19.456 0-210.944 171.52-382.976 382.976-382.976 81.92 0 159.744 25.6 225.792 73.728 8.704 6.144 10.752 18.432 4.096 27.136a19.0464 19.0464 0 0 1-27.136 4.096c-59.392-43.52-129.536-66.048-202.752-66.048-189.44 0-343.552 154.112-343.552 343.552-0.512 11.264-9.216 19.968-19.968 19.968z" fill="#8a8a8a" p-id="1203"></path></svg>
          <el-dialog
            :visible.sync="addUserDialog"
            title="创建群聊"
            width="30%"
          >
            <el-checkbox-group v-model="checkedUsers">
              <el-checkbox v-for="(user,index) in friendList" :label="user.userId" :key="index">{{user.userName}}</el-checkbox>
            </el-checkbox-group>

            <span slot="footer" class="dialog-footer">
             <el-input placeholder="请输入群聊名" style="margin-bottom: 10px"  v-model="createGroupChatName"></el-input>
         <el-button type="primary" @click="createGroup()">创建群聊</el-button>
         </span>
          </el-dialog>



        </div>
              <!--      //所有待处理-->
              <ul v-show="clickIcon=='chat_info'" id="infoList" style="list-style: none;height: 550px;padding: 0px;margin: 20px 0px 0px;width: 180px;height: 39px">
                <li style="margin: 0px;cursor: pointer;height: 40px;background-color: white" v-for="reqRecord in reqRecordList" >
                  <el-avatar style="float: left" shape="square" size="medium" :src="headerPic"></el-avatar>
                  <div style="width: 80px;height: 40px;font-size: 12px;float: left">{{reqRecord.fromUser+":"+reqRecord.content}}
                  </div>
                  <div style="width: 64px;float: right;">
                    <el-button @click="handelRequest('agree',reqRecord)" style="float: left" type="text" size="mini">同意</el-button>
                    <el-button @click="handelRequest('refuse',reqRecord)" style="float: left" type="text" size="mini">拒绝</el-button>
                  </div>
                </li>
              </ul>

      </div>


      <!--    //右侧消息框-->
      <div style="width: 720px;height: 600px;float: right;background-color: #eceaea">
        <div v-show="selectedUser.userName==undefined && selectedGroup.groupName==undefined" style="width: 220px;height: 200px;margin: 188px auto auto;">
          <svg t="1623124103042" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1268" width="200" height="200"><path d="M707.456 391.872C675.136 246.976 530.496 137.6 357.12 137.6 159.936 137.6 0 278.976 0 453.376c0 84.096 37.184 160.448 97.792 216.96 18.688 17.664 19.52 47.168 1.792 65.792l-28.672 30.144s271.36 2.944 286.272 2.944c69.12 0 133.632-17.408 188.288-47.488 101.376-55.68 168.832-155.072 168.832-268.416-0.064-20.992-2.368-41.536-6.848-61.44zM185.984 509.44c-31.04 0-56.064-25.024-56.064-56.064 0-30.976 25.024-56.064 56.064-56.064 30.976 0 56.064 25.088 56.064 56.064 0 31.04-25.088 56.064-56.064 56.064z m171.136 0c-30.976 0-56.064-25.024-56.064-56.064 0-30.976 25.088-56.064 56.064-56.064s56.064 25.088 56.064 56.064c0 31.04-25.088 56.064-56.064 56.064z m173.184-0.064c-0.704 0.064-1.344 0.064-2.048 0.064-30.976 0-56.064-25.024-56.064-56.064 0-30.976 25.088-56.064 56.064-56.064 28.48 0 51.968 21.184 55.552 48.64 0.32 2.496 0.512 4.928 0.512 7.488a55.776 55.776 0 0 1-54.016 55.936z" fill="#666666" p-id="1269"></path><path d="M956.096 809.216l19.584 20.544h-159.296c-1.92 0-3.84 0.128-5.76 0.32-9.856 1.088-19.84 1.728-30.016 1.728-85.184 0-160.192-38.72-203.584-97.344 101.376-55.68 168.832-155.072 168.832-268.416 0-21.056-2.368-41.6-6.848-61.504 13.504-2.112 27.456-3.136 41.6-3.136 134.4 0 243.328 96.32 243.328 215.168 0 57.28-25.344 109.312-66.624 147.84-12.672 11.968-13.184 32.064-1.216 44.8z" fill="#666666" p-id="1270"></path></svg>
        </div>

      </div>
    </div>
</template>

<script>
  import http from '../utils/http'
  import {getFriends} from '@/api/user'
  import messageList from './messageList'
  export default {
    //添加update方法：
    updated : function(){
      this.$nextTick(function(){
        var div = document.getElementById('show_infos');
        var test=document.getElementById('groupChatInfo');
        div.scrollTop = div.scrollHeight;
        test.scrollTop=test.scrollHeight;
      })
    },
    components:{
      messageList,
    },
    data () {
      var check = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('年龄不能为空'));
        }
        callback();
      };

      return {
        clickIcon:'chat_info',
        headerPic: '',
        websocket: null, // WebSocket对象
        messageValue: '', // 消息内容
        friendList: [], //用户信息

        selectedUser: {},
        selectedGroup:{},
        currentUser: this.$store.getters.getUser,
        friendMessageMap:new Map(),
        friendListMap:new Map(),
        searchInfo:'',
        //所有群聊
        groupChatList:[],
        //添加好友弹唱窗口
        addUserDialog:false,
        checkedUsers:[],
        createGroupChatName:'',
        reqRecordList:[],


        form: {},
        dialogVisible2: false,//弹窗
        dialogVisible: false,
        file:{},

        rules: {
          userName: [
            {validator: check, trigger: 'blur'}
          ],
          userId: [
            {validator: check, trigger: 'blur'}
          ],
          age: [
            {validator: check, trigger: 'blur'}
          ]
        },
      }
    },
    created () {
      // this.connectWebSocket()
      // this.getFriends()
      this.getAllReqRecord();
      this.headerPic='http://localhost:8080/up/getPhoto/'+this.currentUser.avatarPath
    },
    methods: {
      // 发送消息
      sendMessage: function (type) {
        if (type == 1) {
          var socketMsg = {fromUser: this.currentUser, msg: this.messageValue, toUser: this.selectedUser}
          this.friendMessageMap.get(this.selectedUser.userId).push({
            fromUser: this.currentUser.userId,
            msg: this.messageValue,
            toUser: this.selectedUser.userId,
            date: new Date()
          })

          this.$forceUpdate()
          // if (this.aisle == "") {
          //   //群聊.
          //   socketMsg.type = 0;
          // } else {
          //单聊.
          socketMsg.type = 1
          // }
          this.websocket.send(JSON.stringify(socketMsg))
          this.messageValue = '';
        } else if (type == 0) {
          var socketMsg = {fromUser: this.currentUser, msg: this.messageValue, groupId: this.selectedGroup.eid, type: 0}
          this.websocket.send(JSON.stringify(socketMsg))
          this.messageValue = '';
        }
      },
      showInfo: function (people, aisle) {
        this.$notify({
          title: '当前在线人数：' + people,
          message: '您的频道号：' + aisle,
          duration: 0
        })
      },
      getName (userId) {
        return this.friendListMap.get(userId).userName
      },
      changeSelect (operate) {
        this.clickIcon = operate
        this.selectedUser = {}
        this.selectedGroup = {}
        // console.log(this.clickIcon)
        // this.$forceUpdate()
        this.$forceUpdate()
        if (operate == 'groupChat') {
          this.getAllGroup()
        }
        if(operate =='chat_info'){
          this.getAllReqRecord();
        }
        if(operate=='contact'){
          this.getFriends();
        }
      },
      //查询当前用户所在的群
      getAllGroup () {
        http.get("/groupChat/getGroup", {
          userId: this.currentUser.userId
        }).then((response) => {
          this.groupChatList = response.data
          console.log(this.groupChatList)
        })
      },
      selectGroup (group) {
        this.selectedGroup = group
        this.selectedUser = {}
        this.$forceUpdate()
      },
      createGroup () {
        console.log(this.checkedUsers)
        if(this.createGroupChatName==''){
          this.$message.warning("请输入群聊名再创建")
          return
        }
        let users=''
        for(let i = 0; i<this.checkedUsers.length; i++){
          users+=this.checkedUsers[i]+":"
        }
        let createGroupDto={
          users:this.checkedUsers,
          createGroupName:this.createGroupChatName,
          lord:this.currentUser.userId
        }
        users=users.substring(0,users.length-1)
        http.post('groupChat/createGroup',createGroupDto).then((res) => {
          if(res.data.code==200){
            this.$message.success(res.data.message)
            this.addUserDialog=false
            if(this.clickIcon=='groupChat'){
              this.getAllGroup()
            }
          }else {
            this.$message.error(res.data.message)
          }
        })
      },
      getAllReqRecord(){
        http.get("user/getReqRecordById", {
          userId:this.currentUser.userId
        }).then((res)=>{
          this.reqRecordList=res.data;
          this.$forceUpdate()
          console.log(this.reqRecordList)
        })
      },
      handelRequest(type,reqRecord){
        if(type=='agree'){
          reqRecord.status='已同意'
        }else{
          reqRecord.status='已拒绝'
        }
        http.post('user/handleReqRecord',reqRecord).then((res)=>{
          this.getAllReqRecord();
          if(res.data.code==200){
            this.$message.success(res.data.message);
          }else{
            this.$message.error(res.data.message);
          }
        })

      },
      addFriend(){
        http.get('user/addFriend',{
          userId:this.currentUser.userId,
          friendId:this.searchInfo,
        }).then((res)=>{
          if(res.data.code==200){
            this.$message.success(res.data.message);
          }else if(res.data.code==400){
            this.$message.warning(res.data.message);
          }else{
            this.$message.error(res.data.message);
          }
          this.searchInfo='';
        })
      },
      handleBeforeUpload (file) {
        if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
          this.$message({
            type:'warning',
            message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
          })
        }
        let size = file.size / 1024 / 1024 / 2
        if (size > 2) {
          this.$message({
            type:'warning',
            message: '图片大小必须小于2M'
          })
        }
        // this.file=file;
      },
      handleChange(file,fileList){
        this.file=fileList[fileList.length-1];
        //此处预览照片
        this.headerPic=URL.createObjectURL(this.file.raw);
        // console.log(fileList)
        // console.log(file)
      },
      uploadFile(){
        let fd = new FormData();//通过form数据格式来传
        let userId=this.currentUser.userId;
        fd.append("file", this.file.raw); //传文件
        fd.append('userId',userId)
        console.log(fd.get('file'));
        this.dialogVisible = true;
        http.upload('/up/uploadHead',fd,{
          'Content-Type': 'multipart/form-data'
        }).then((res)=>{
          http.get('user/getUserById',{
            userId:userId
          }).then((res) => {
            this.$store.commit('SET_USER', res.data);
            this.currentUser=res.data;
            console.log(this.currentUser)
            this.headerPic='http://localhost:8080/up/getPhoto/'+this.currentUser.avatarPath;
          })
        })

      },
      handleAvatarSuccess(res, file) {
        this.headerPic = URL.createObjectURL(file.raw);
        console.log(this.headerPic)
      },
    }
  }
</script>

<style scoped>

  #userList li {
    background-color: white;
    width: 100%;
    height: 40px;
    line-height: 40px;
    color: black;
    margin-bottom: 2px;
  }

  body {
    background-color: #ebebeb;
    font-family: -apple-system;
    font-family: "-apple-system", "Helvetica Neue", "Roboto", "Segoe UI", sans-serif;
  }

  .chat-sender {
    clear: both;
    font-size: 80%;
    float: left;
  }

  .chat-sender div:nth-of-type(1) {
    float: left;
  }

  .chat-sender div:nth-of-type(2) {
    margin: 0 50px 2px 50px;
    padding: 0px;
    color: #848484;
    font-size: 70%;
    text-align: left;
  }

  .chat-sender div:nth-of-type(3) {
    background-color: white;
    /*float: left;*/
    margin: 0 50px 10px 50px;
    padding: 10px 10px 10px 10px;
    border-radius: 7px;
    text-indent: -12px;
  }

  .chat-receiver {
    clear: both;
    font-size: 80%;
    float: right;
  }

  .chat-receiver div:nth-of-type(1) {
    float: right;
  }

  .chat-receiver div:nth-of-type(2) {
    margin: 0px 50px 2px 50px;
    padding: 0px;
    color: #848484;
    font-size: 70%;
    text-align: right;
  }

  .chat-receiver div:nth-of-type(3) {
    /*float:right;*/
    background-color: #b2e281;
    margin: 0px 50px 10px 50px;
    padding: 10px 10px 10px 10px;
    border-radius: 7px;
  }

  .chat-receiver div:first-child img,
  .chat-sender div:first-child img {
    width: 40px;
    height: 40px;
    /*border-radius: 10%;*/
  }

  .chat-left_triangle {
    height: 0px;
    width: 0px;
    border-width: 6px;
    border-style: solid;
    border-color: transparent white transparent transparent;
    position: relative;
    left: -22px;
    top: 3px;
  }

  .chat-right_triangle {
    height: 0px;
    width: 0px;
    border-width: 6px;
    border-style: solid;
    border-color: transparent transparent transparent #b2e281;
    position: relative;
    right: -22px;
    top: 3px;
  }

  .chat-notice {
    clear: both;
    font-size: 70%;
    color: white;
    text-align: center;
    margin-top: 15px;
    margin-bottom: 15px;
  }

  .chat-notice span {
    background-color: #cecece;
    line-height: 25px;
    border-radius: 5px;
    padding: 5px 10px;
  }

</style>
<style>
  .chatBox_header{
    width: 180px;
    height: 30px;
  }
  .chatBox_header  .el-input__inner {
    width: 140px!important;
    height: 30px!important;
  }
  .chatBox_header .el-input__prefix{
    top:-5px!important;
  }
</style>
<!-- -->

